<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        canvas{border: 1px solid #aaa;}
    </style>
</head>
<body>
    <canvas width="600" height="400" class="myCanvas">
        当前的浏览器版本不支持，请升级浏览器
    </canvas>

    <script>
        var canvas = document.getElementsByClassName('myCanvas')[0];
        var ctx = canvas.getContext('2d');

        function Rect(x,y,w,h,color) {
            this.x = x;
            this.y = y;
            this.w = w;
            this.h = h;
            this.color = color;
        }
        Rect.prototype = {
            //更新
            upDate(){
                this.x++;
                this.render(); //更新之后直接渲染
            },
            //渲染
            render(){
                ctx.fillStyle = this.color;
                ctx.fillRect(this.x,this.y,this.w,this.h);
            }
        };
        var r = new Rect(100,100,50,50,'red');
        var r1 = new Rect(100,200,50,50,'blue');

        //初始化动画
        r.render();
        r1.render();
        setInterval(function(){
            //统一清除画布
            ctx.clearRect(0,0,canvas.width,canvas.height);

            r.upDate();
            r1.upDate();
        },100);
    </script>
</body>
</html>
